<template>
  <el-dialog
    title="基础设置"
    :visible.sync="visible"
    :before-close="handleClose"
    width="60%"
  >
    <el-form
      ref="form"
      :model="form"
      :rules="form"
      style="height: 500px; overflow-y: scroll;"
    >
      <el-form-item v-if="listType === 'add'" label="商品名称">
        <div v-if="setLock == 'single'" style="width:80%;">{{ form.name }}</div>
        <span v-else>这是一款即将上架的商品名称</span>
      </el-form-item>
      <el-form-item v-if="listType === 'edit'" label="商品名称">
        <el-input
          v-model="form.name"
          disabled
          class="form-input"
          size="medium"
        ></el-input>
      </el-form-item>
      <el-form-item
        label="活动库存"
        prop="stock"
        :rules="[{ required: true, message: ' 活动库存不能为空' }]"
      >
        <!-- <el-input v-model.number="form.stock"
                  style="width:200px;"></el-input>
                  ,
                    {type: "number",message: "活动库存必须为数字值"},
                    {min: form.goods_stock,message: "活动库存不能大于商品总库存"}
                  -->
        <el-input-number
          v-model="form.stock"
          :precision="0"
          :step="1"
          :min="0"
          :max="form.goods_stock ? form.goods_stock : 100000000000000"
          :controls="false"
          size="medium"
        ></el-input-number
        >&nbsp;&nbsp;
        <span v-if="setLock == 'single'"
          >当前总库存：{{ form.goods_stock }}</span
        >
        <span v-if="listType == 'edit'"
          >当前总库存：{{ form.goods_stock }}</span
        >
        <span style="color:#909399;font-size:12px;"
          >&nbsp;&nbsp;若活动库存等于总库存，则活动开始前该商品不能原价购买</span
        >
      </el-form-item>
      <el-form-item
        label="初始参团人数"
        prop="start_nums"
        :rules="{ required: true, message: '请输入参团人数', trigger: 'blur' }"
      >
        <el-input-number
          v-model="form.start_nums"
          :precision="0"
          :step="1"
          :min="0"
          :controls="false"
          size="medium"
        ></el-input-number>
        <span style="color:#909399;font-size:12px;"
          >&nbsp;&nbsp;前端会显示初始参团人数+实际参团人数；主要目的为活跃活动气氛效果。</span
        >
      </el-form-item>
      <div v-if="listType == 'add'">
        <el-form-item
          label="开团次数限制"
          prop="open_limit"
          :rules="{
            required: true,
            message: '请输入开团次数限制',
            trigger: 'blur'
          }"
        >
          每个用户可开团次数最多
          <el-input-number
            v-model="form.open_limit"
            :precision="0"
            :step="1"
            :min="0"
            :controls="false"
            size="medium"
          ></el-input-number>
          次
          <span style="color:#909399;font-size:12px;"
            >&nbsp;&nbsp;0表示不限次数</span
          >
        </el-form-item>
        <el-form-item
          label="参团次数限制"
          prop="join_limit"
          :rules="{
            required: true,
            message: '请输入参团次数限制',
            trigger: 'blur'
          }"
        >
          每个用户可参团次数最多&nbsp;&nbsp;
          <el-input-number
            v-model="form.join_limit"
            :precision="0"
            :step="1"
            :min="0"
            :controls="false"
            size="medium"
          ></el-input-number>
          次
          <span style="color:#909399;font-size:12px;"
            >&nbsp;&nbsp;0表示不限次数</span
          >
        </el-form-item>
        <el-form-item
          label="单次购买数量"
          prop="buy_limit"
          :rules="{
            required: true,
            message: '请输入单次购买数量',
            trigger: 'blur'
          }"
        >
          每个用户开团或者参团时购买件数最多&nbsp;&nbsp;
          <el-input-number
            v-model="form.buy_limit"
            :precision="0"
            :step="1"
            :min="0"
            :controls="false"
            size="medium"
          ></el-input-number>
          件
          <span style="color:#909399;font-size:12px;"
            >&nbsp;&nbsp;0表示不限件数</span
          >
        </el-form-item>
        <el-form-item label="赠送优惠劵">
          <div style="margin-bottom:20px;">
            <el-checkbox v-model="form.assemble_success" label="1"
              >拼团成功</el-checkbox
            >
            <el-select
              v-model="form.assemble_success_value"
              placeholder="请选择优惠劵"
              style="margin-right: 10px;"
              :disabled="!form.assemble_success"
            >
              <el-option
                v-for="item in optionsY"
                :key="item.lg_coupon_id"
                :label="item.title"
                :value="item.lg_coupon_id"
              >
              </el-option>
            </el-select>
            <span style="font-size:14px;">单人最多送</span>

            <el-input-number
              v-model="form.assemble_success_num"
              :precision="0"
              :step="1"
              :min="0"
              :controls="false"
              :disabled="!form.assemble_success"
              style="margin:0 10px;"
              size="medium"
            ></el-input-number>
            次

            <span style="color:#909399;font-size:12px;"
              >&nbsp;&nbsp;0表示不限次数</span
            >
          </div>
          <div>
            <el-checkbox v-model="form.assemble_fail" label="2"
              >拼团失败</el-checkbox
            >
            <el-select
              v-model="form.assemble_fail_value"
              placeholder="请选择优惠劵"
              style="margin-right: 10px;"
              :disabled="!form.assemble_fail"
            >
              <el-option
                v-for="item in optionsY"
                :key="item.lg_coupon_id"
                :label="item.title"
                :value="item.lg_coupon_id"
              >
              </el-option>
            </el-select>
            <span style="font-size:14px;">单人最多送</span>

            <el-input-number
              v-model="form.assemble_fail_num"
              :precision="0"
              :step="1"
              :min="0"
              :controls="false"
              :disabled="!form.assemble_fail"
              style="margin:0 10px;"
              size="medium"
            ></el-input-number>
            次

            <span style="color:#909399;font-size:12px;"
              >&nbsp;&nbsp;0表示不限次数</span
            >
          </div>
        </el-form-item>
      </div>
      <el-form-item
        label="排序"
        prop="sort"
        :rules="{ required: true, message: '请输入排序', trigger: 'blur' }"
      >
        <el-input-number
          v-model="form.sort"
          :precision="0"
          :step="1"
          :min="0"
          :max="99"
          :controls="false"
          size="medium"
        ></el-input-number>
        <span style="color:#909399;font-size:12px;">
          &nbsp;&nbsp;支持0-99设置，前、后台参加活动商品列表均按照此排序排列，数字越大越排在前</span
        >
      </el-form-item>
      <el-form-item
        v-if="listType == 'add'"
        label="成团人数"
        prop="need_nums"
        :rules="{ required: true, message: '请输入成团人数', trigger: 'blur' }"
      >
        <el-input-number
          v-model="form.need_nums"
          :precision="0"
          :step="1"
          :min="2"
          :controls="false"
          size="medium"
        ></el-input-number>
        人
        <span style="color:#909399;font-size:12px;">
          拼团成功需要参与购买的人数，需大于1人</span
        >
      </el-form-item>
      <el-form-item
        v-if="listType == 'add'"
        label="拼团价格"
        prop="unite_price"
        :rules="{ required: true, message: '请输入拼团价格', trigger: 'blur' }"
      >
        <div v-if="setLock == 'all'">
          <el-input-number
            v-model="form.unite_price"
            :precision="2"
            :step="1"
            :min="0"
            :controls="false"
            size="medium"
          ></el-input-number>
          元
        </div>
        <Table v-else :data="tableData">
          <!--  :span-method='objectSpanMethod' -->
          <el-table-column
            v-if="skuType[0]"
            prop="sku_type_name[0]"
            :label="skuType[0]"
            width="180"
          >
          </el-table-column>
          <el-table-column
            v-if="skuType[1]"
            prop="sku_type_name[1]"
            :label="skuType[1]"
            width="180"
          >
          </el-table-column>
          <el-table-column
            v-if="skuType[2]"
            prop="sku_type_name[2]"
            :label="skuType[2]"
            width="180"
          >
          </el-table-column>
          <el-table-column label="是否参加">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.status"
                active-color="#13ce66"
                inactive-color="#ff4949"
              >
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column label="商品库存" property="sku_stock">
          </el-table-column>
          <el-table-column label="活动参加库存">
            <template slot-scope="scope">
              <el-input-number
                v-model.lazy="scope.row.join_stock"
                size="medium"
                style="width:100%;"
                :precision="0"
                :min="1"
                :max="scope.row.sku_stock"
                placeholder="请输入参加库存"
                :controls="false"
                @blur="
                  // eslint-disable-next-line vue/camelcase
                  !scope.row.join_stock ? (scope.row.join_stock = 1) : ''
                "
              ></el-input-number>
            </template>
          </el-table-column>
          <el-table-column label="销售价格" property="sku_price">
          </el-table-column>
          <el-table-column label="拼团价格">
            <template slot-scope="scope">
              <el-input-number
                v-model.lazy="scope.row.join_price"
                size="medium"
                style="width:100%;"
                :precision="2"
                placeholder="请输入拼团价格"
                :min="1"
                :max="scope.row.sku_price"
                :controls="false"
                @blur="
                  // eslint-disable-next-line vue/camelcase
                  !scope.row.join_price ? (scope.row.join_price = 1) : ''
                "
              ></el-input-number>
            </template>
          </el-table-column>
        </Table>
      </el-form-item>
      <el-form-item
        v-else
        label="拼团价格"
        prop="unite_price"
        :rules="{ required: true, message: '请输入拼团价格', trigger: 'blur' }"
      >
        <div class="tables">
          <el-table
            :data="tableData"
            :header-row-style="{
              color: '#333333',
              fontSize: '14px',
              letterSpacing: '0.39px'
            }"
          >
            <!-- :span-method='objectSpanMethod' -->
            <el-table-column
              v-if="skuType[0]"
              prop="sku_type_name[0]"
              :label="skuType[0]"
              width="180"
            >
            </el-table-column>
            <el-table-column
              v-if="skuType[1]"
              prop="sku_type_name[1]"
              :label="skuType[1]"
              width="180"
            >
            </el-table-column>
            <el-table-column
              v-if="skuType[2]"
              prop="sku_type_name[2]"
              :label="skuType[2]"
              width="180"
            >
            </el-table-column>
            <el-table-column label="是否参加">
              <template slot-scope="scope">
                <el-switch
                  v-model="scope.row.status"
                  active-color="#13ce66"
                  inactive-color="#ff4949"
                >
                </el-switch>
              </template>
            </el-table-column>
            <el-table-column label="商品库存" property="sku_stock">
            </el-table-column>
            <el-table-column label="活动参加库存">
              <template slot-scope="scope">
                <el-input-number
                  v-model.lazy="scope.row.join_stock"
                  size="medium"
                  style="width:100%;"
                  :precision="0"
                  :min="0"
                  :max="scope.row.sku_stock"
                  placeholder="请输入参加库存"
                  :controls="false"
                ></el-input-number>
              </template>
            </el-table-column>
            <el-table-column label="销售价格" property="sku_price">
            </el-table-column>
            <el-table-column label="拼团价格">
              <template slot-scope="scope">
                <el-input-number
                  v-model.lazy="scope.row.join_price"
                  size="medium"
                  style="width:100%;"
                  :precision="2"
                  placeholder="请输入拼团价格"
                  :min="0"
                  :max="scope.row.sku_price"
                  :controls="false"
                ></el-input-number>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="handleClose">取 消</el-button>
      <el-button v-if="listType == 'add'" type="primary" @click="submit"
        >确 定</el-button
      >
      <el-button v-else type="primary" @click="submitE">确 定</el-button>
    </div>
  </el-dialog>
</template>
<script>
import { COUPON_LIST } from "@/service/shop";
import {
  ADDASSEMBLEBASECONFGOODS,
  EDITASSEMBLEBASECONFGOODS,
  GETGOODSSKU
} from "../../service";

export default {
  props: {
    assembleId: {
      type: String,
      default: ""
    },
    typeP: {
      type: String,
      default: ""
    },
    visible: {
      type: Boolean,
      default: false
    },
    datas: {
      type: Object,
      default: () => {}
    },
    listType: {
      type: String,
      default: ""
    },
    listDataAll: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      form: {
        name: "",
        goods_id: 0,
        goods_stock: "",
        stock: 0,
        start_nums: 0,
        open_limit: 0,
        join_limit: 0,
        buy_limit: 0,
        sort: 0,
        unite_price: 0,
        need_nums: 0,
        goods_id_arr: "",
        assemble_success: false,
        assemble_success_value: "",
        assemble_success_num: 0,
        assemble_fail: false,
        assemble_fail_value: "",
        assemble_fail_num: 0
      },
      optionsY: [],
      tableData: [],
      skuType: [],
      setLock: ""
    };
  },
  watch: {
    visible(v) {
      if (v) {
        if (this.listType === "add") {
          this.add(this.datas, this.typeP);
        } else {
          this.edit(this.datas, this.typeP);
        }
      }
    }
  },
  created() {
    this.getCoupon();
  },
  methods: {
    handleClose() {
      this.setLock = "";
      this.$emit("outDialog", false);
    },
    init() {
      this.form = {
        name: "",
        goods_id: "",
        goods_stock: "",
        stock: 0,
        start_nums: 0,
        open_limit: 0,
        join_limit: 0,
        buy_limit: 0,
        sort: 0,
        unite_price: 0,
        need_nums: 0,
        goods_id_arr: "",
        assemble_success: false,
        assemble_success_value: "",
        assemble_success_num: 0,
        assemble_fail: false,
        assemble_fail_value: "",
        assemble_fail_num: 0
      };
    },
    async add(e, type) {
      this.setLock = type;
      this.init();
      if (type === "single") {
        this.form.name = e.goods_name;
        this.form.goods_id = e.goods_id;
        this.form.goods_stock = e.goods_stock;
        this.getSKU(e.goods_id);
      } else {
        let arr = [];
        this.listDataAll.forEach(ele => {
          arr.push(ele.goods_id);
        });
        this.form.goods_id = arr.join(",");
      }
    },
    edit(e, type) {
      this.setLock = type;
      this.form.name = e.goods_name;
      this.form.goods_id = e.goods_id;
      this.form.stock = e.stock;
      this.form.sort = e.sort;
      this.form.goods_stock = e.goods_stock;
      this.form.start_nums = e.start_nums;
      this.getSKU(e.goods_id, "edit");
    },
    async getSKU(id) {
      this.tableData = [];
      this.skuType = [];
      await GETGOODSSKU({
        activity_id: this.assembleId,
        activity_type: 1,
        goods_id: id
      }).then(({ code, data, msg }) => {
        if (code === 200) {
          data.forEach(ele => {
            ele.status = ele.status === 1;
            ele.sku_price = parseFloat(ele.sku_price);
            ele.sku_type_name = ele.sku_type_name.split(",");
          });
          this.tableData = data;
          this.skuType = data[0].attr_names.split(",");
        } else {
          this.$message.error(msg);
        }
      });
    },
    async submit() {
      let arr = [];
      let content1 = "";
      let content2 = "";
      let num = 0;

      if (this.setLock === "single") {
        this.tableData.forEach(ele => {
          if (ele.status) num += ele.join_stock;

          arr.push({
            uniqueKey: ele.uniqueKey,
            status: ele.status ? 1 : 0,
            join_price: ele.join_price,
            join_stock: ele.join_stock
          });
        });
        if (num > this.form.stock) {
          this.$message.error("参加活动的规格库存总数不能大于活动库存总数！");
          return;
        }
        if (num === 0) {
          this.$message.error("参加活动的规格库存总数必须大于1！");
          return;
        }
      }
      content1 = this.form.assemble_success_value
        ? this.form.assemble_success_value +
          "," +
          this.form.assemble_success_num
        : "";
      content2 = this.form.assemble_fail_value
        ? this.form.assemble_fail_value + "," + this.form.assemble_fail_num
        : "";
      let prams = {
        assemble_id: this.assembleId,
        stock: this.form.stock,
        start_nums: this.form.start_nums,
        open_limit: this.form.open_limit,
        join_limit: this.form.join_limit,
        buy_limit: this.form.buy_limit,
        sort: this.form.sort,
        need_nums: this.form.need_nums,
        goods_id_arr: this.form.goods_id,
        goods: JSON.stringify(arr),
        assemble_success: this.form.assemble_success ? 1 : 0,
        assemble_success_content: content1,
        assemble_fail: this.form.assemble_fail ? 1 : 0,
        assemble_fail_content: content2
      };
      await this.$refs["form"].validate(valid => {
        if (valid) {
          ADDASSEMBLEBASECONFGOODS(prams).then(({ code, msg }) => {
            if (code === 200) {
              this.$emit("outDialog", false, "submit");
            }
            this.$message({
              message: msg,
              type: code === 200 ? "success" : "error"
            });
          });
        } else {
          return false;
        }
      });
    },
    async submitE() {
      let arr = [];
      let num = 0;
      this.tableData.forEach(ele => {
        if (ele.status) num += ele.join_stock;
        arr.push({
          uniqueKey: ele.uniqueKey,
          status: ele.status ? 1 : 0,
          join_price: ele.join_price,
          join_stock: ele.join_stock
        });
      });
      if (num > this.form.stock) {
        this.$message.error("参加活动的规格库存总数不能大于活动库存总数！");
        return;
      }
      let prams = {
        assemble_id: this.assembleId,
        stock: this.form.stock,
        start_nums: this.form.start_nums,
        sort: this.form.sort,
        goods_id: this.form.goods_id,
        goods: JSON.stringify(arr)
      };
      await this.$refs["form"].validate(valid => {
        if (valid) {
          EDITASSEMBLEBASECONFGOODS(prams).then(({ code, msg }) => {
            if (code === 200) {
              this.$emit("outDialog", false, "submit");
            }
            this.$message({
              message: msg,
              type: code === 200 ? "success" : "error"
            });
          });
        } else {
          return false;
        }
      });
    },
    // objectSpanMethod ({ row, column, rowIndex, columnIndex }) {
    //   if (columnIndex === 0) {
    //     if (this.sku_type[1] && !this.sku_type[2]) {
    //       if (rowIndex % this.sku_type[1].children.length === 0) {
    //         return {
    //           rowspan: this.sku_type[1].children.length,
    //           colspan: 1
    //         }
    //       } else {
    //         return {
    //           rowspan: 0,
    //           colspan: 0
    //         }
    //       }
    //     } else if (this.sku_type[1] && this.sku_type[2]) {
    //       if (
    //         rowIndex %
    //         (this.sku_type[1].children.length *
    //           this.sku_type[2].children.length) ===
    //         0
    //       ) {
    //         return {
    //           rowspan:
    //             this.sku_type[1].children.length *
    //             this.sku_type[2].children.length,
    //           colspan: 1
    //         }
    //       } else {
    //         return {
    //           rowspan: 0,
    //           colspan: 0
    //         }
    //       }
    //     }
    //   }
    //   if (columnIndex === 1) {
    //     if (this.sku_type[2]) {
    //       if (rowIndex % this.sku_type[2].children.length === 0) {
    //         return {
    //           rowspan: this.sku_type[2].children.length,
    //           colspan: 1
    //         }
    //       } else {
    //         return {
    //           rowspan: 0,
    //           colspan: 0
    //         }
    //       }
    //     }
    //   }
    // },
    async getCoupon() {
      await COUPON_LIST({ type: 1, page: 1, pageshow: 10000 }).then(
        ({ code, data }) => {
          if (code === 200) {
            this.optionsY = data.list;
          }
        }
      );
    }
  }
};
</script>
